#coding=utf-8
from flask import render_template, redirect, request, url_for, flash
from flask_login import login_user,logout_user, login_required,current_user
from app.plan import plan
from app.plan.forms import CaseForm
from app.models import User,Plan,TestCase
from datetime import datetime
from app import db
from api.request_api import Request_Api,get_subjectName,get_requestType
from api import test_report
import time


@plan.before_app_request
def before_request():
	if current_user.is_authenticated:
		current_user.ping()
	pass


def get_case(plan_id):
	case_list = []
	info = TestCase.query.filter_by(plan_id=plan_id).all()
	#		info=db.session.query(TestCase).filter(TestCase.plan_id==requests.get('plan_id')).all()
	'''按plan_id遍历用例，用[(a1, b1, c1, d1), (a2, b2, c2, d2)]形式保存于case_list'''
	for i in info:
		t = (i.host, i.url, i.method, i.parameter, i.expectation, i.depiction)
		case_list.append(t)
	return case_list


@plan.route('/run',methods=['GET', 'POST'])
def plan_run():
	#用例执行起始时间
	star_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	#ctime1 = time.mktime(datetime.now().timetuple())
	ctime1 = datetime.now()
	
	web_requests = request.args
	# 获取项目名称
	subject_name= get_subjectName(int(web_requests.get('subject_id')))
	# 获取项目plan_id
	plan_id = web_requests.get('plan_id')
	
	# 测试报告字典
	report_info = {'all_cases': [], 'pass_cases': [], 'error_cases': [], 'failed_cases': []}
	# 测试报告字典-全部用例[项目名称, 序号, 用例名称, 接口地址, 请求方式, 测试结果, '详细（标题不传参）',返回内容]
	all_cases_list = report_info['all_cases']
	# 测试报告字典-通过用例
	pass_cases_list = report_info['pass_cases']
	# 测试报告字典-失败用例
	failed_cases_list = report_info['failed_cases']
	# 测试报告字典-异常用例
	error_cases_list = report_info['error_cases']
	# 测试用例list
	list=get_case(plan_id=plan_id)
	
	'''用例个数'''
	case_count=len(list)
	
	'''遍历用例case_list'''
	for i in range(case_count):
		api_info=Request_Api(host=str(list[i][0]),url=str(list[i][1]),method=str(list[i][2]),parameter=str(list[i][3]),expectation=str(list[i][4]),depiction=str(list[i][5])).api()
		if api_info['api_sta']=='pass':
			all_cases_list.append([subject_name, i+1, str(list[i][5]), str(list[i][1]),get_requestType((list[i][2])), '通过', '详细', api_info['api_res']])
			pass_cases_list.append([subject_name, i+1, str(list[i][5]), str(list[i][1]), get_requestType((list[i][2])), '通过', '详细', api_info['api_res']])
		elif api_info['api_sta']=='failed':
			all_cases_list.append([subject_name, i+1, str(list[i][5]), str(list[i][1]), get_requestType((list[i][2])), '失败', '详细', api_info['api_res']])
			failed_cases_list.append([subject_name, i+1, str(list[i][5]), str(list[i][1]), get_requestType((list[i][2])), '失败', '详细', api_info['api_res']])
		elif api_info['api_sta']=='error':
			all_cases_list.append([subject_name, i+1, str(list[i][5]), str(list[i][1]),get_requestType((list[i][2])), '错误', '详细', api_info['api_res']])
			error_cases_list.append([subject_name, i+1, str(list[i][5]), str(list[i][1]), get_requestType((list[i][2])), '错误', '详细', api_info['api_res']])
	
	#用例执行结束时间
	end_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	#ctime2 = time.mktime(datetime.now().timetuple())
	ctime2 = datetime.now()
	
	#用例通过率
	case_percent= '{:.2%}'.format(len(pass_cases_list)/len(list))
	
	test_report.HTML_REPORT( html_title='html_title',
		pie_theme='pie_theme',
		#test_info=[开始时间, 结束时间, 用时,用例数量, 通过率, 测试域名]
		test_info=[star_time, end_time, ctime2-ctime1,case_count, case_percent, list[0][0]],
		report_table_title=['项目名称', '用例编号', '用例名称', '接口地址', '接口方法', '测试结果', '详细信息'],
		report_cases=report_info).creat_report(dir="D:/FlskTest/app/templates/test_report/test_demo.html")

	return render_template('test_report/test_demo.html', case_lists=report_info)
	# return render_template('test.html', case_lists=type(web_requests.get('subject_id')))


@plan.route('/edit',methods=['GET', 'POST'])
def plan_edit():
	form=CaseForm()
	requests = request.args
	# 字典形式将requests的内容传递到plan_edit.html
	context={
		'plan_id':requests.get('plan_id'),
		'plan_name':requests.get('plan_name'),
		'plan_info':requests.get('plan_info')
			}
	if form.validate_on_submit():
		post_data=TestCase(
			host=form.host.data,
			url=form.url.data,
			method=form.method.data,
		    parameter =form.parameter.data,
			expectation =form.expectation.data,
			depiction=form.depiction.data,
			plan_id=requests.get('plan_id')
		)
		db.session.add(post_data)
		db.session.commit()
		return redirect(url_for('.plan_edit',**context))
	case_lists=TestCase.query.filter_by(plan_id=requests.get('plan_id')).order_by(TestCase.id.asc()).all()
	# 将获取到的plan_id，plan_id，参数形式传入跳转的页面
	return render_template('plan/plan_edit.html',form=form,**context,case_lists=case_lists)

@plan.route('/delete/<plan_id>',methods=['GET','POST'])
def plan_delete(plan_id):
	db.session.query(Plan).filter(Plan.id ==plan_id).update({"status":2})
	db.session.commit()
	return redirect(url_for('main.index'))



@plan.route('/update_case/<id>',methods=['POST'])
def update_case(id):
	#通过 to_dict() 转成 dict 类型的
	dates = request.form.to_dict()
	
	#更新TestCase表对应字段
	host = list(dates.values())[0]
	url = list(dates.values())[1]
	method = list(dates.values())[2]
	parameter = list(dates.values())[3]
	expectation=list(dates.values())[4]
	depiction = list(dates.values())[5]
	update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	
	# 查询出对应id的testcase
	case_info = TestCase.query.filter_by(id =id).first()
	# 更新对应的字段
	case_info.host = host
	case_info.url = url
	case_info.method = method
	case_info.parameter = parameter
	case_info.expectation = expectation
	case_info.depiction = depiction
	case_info.update_time = update_time
	db.session.commit()
	
	#通过plan_id查询plan_id,plan_name,plan_info
	plan_id = case_info.plan_id
	plan_data=Plan.query.filter_by(id =plan_id).first()
		
	context={
		'plan_id':plan_id,
		'plan_name':plan_data.plan_name,
		'plan_info':plan_data.plan_info
			}
	
	return redirect(url_for('.plan_edit',**context))


@plan.route('/test_report/<plan_id>',methods=['GET','POST'])
def plan_testreport(plan_id):
	 return render_template('test_report/test_demo.html')